/*
 * @lc app=leetcode.cn id=515 lang=golang
 *
 * [515] 在每个树行中找最大值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func largestValues(root *TreeNode) (ans []int) {
	var recursion func(nodes []*TreeNode)
	recursion = func(nodes []*TreeNode) {
		if len(nodes) == 0 {
			return
		}

		maxValue := math.MinInt64
		temp := make([]*TreeNode, 0)
		for i := 0; i < len(nodes); i++ {
			if nodes[i] == nil {
				continue
			}
			maxValue = max(maxValue, nodes[i].Val)
			temp = append(temp, nodes[i].Left, nodes[i].Right)
		}

		if maxValue != math.MinInt64 {
			ans = append(ans, maxValue)
		}

		recursion(temp)
	}
	recursion([]*TreeNode{root})
	return
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

// @lc code=end

